from abc import ABC, abstractmethod
from datetime import datetime, timedelta


class Vehicle(ABC):
    """车辆基类 - 定义所有车辆共有的接口"""

    def __init__(self, brand, model, year, license_plate=None):
        self.brand = brand
        self.model = model
        self.year = year
        self.license_plate = license_plate
        self.created_at = datetime.now()

    @abstractmethod
    def get_info(self):
        """获取车辆信息 - 抽象方法，子类必须实现"""
        pass

    @abstractmethod
    def perform_action(self):
        """执行特定动作 - 抽象方法，子类必须实现"""
        pass

    @abstractmethod
    def calculate_value(self):
        """计算价值 - 抽象方法，子类必须实现"""
        pass

    def get_common_info(self):
        """获取通用信息 - 具体方法，子类可以继承"""
        return f"{self.brand} {self.model} ({self.year})"


class ManufacturerVehicle(Vehicle):
    """厂家视角的车辆类"""

    def __init__(self, brand, model, year, production_cost, target_price,
                 warranty_years, recall_status=False):
        super().__init__(brand, model, year)
        self.production_cost = production_cost
        self.target_price = target_price
        self.warranty_years = warranty_years
        self.recall_status = recall_status
        self.technical_specs = {}

    def get_info(self):
        """多态实现 - 厂家关注技术规格和成本"""
        base_info = self.get_common_info()
        specs = ", ".join([f"{k}: {v}" for k, v in self.technical_specs.items()])
        return (f"{base_info} | 生产成本: {self.production_cost}元 | "
                f"目标售价: {self.target_price}元 | 技术规格: {specs}")

    def perform_action(self):
        """多态实现 - 厂家执行生产相关动作"""
        if self.recall_status:
            return f"正在处理{self.brand} {self.model}的召回事宜"
        else:
            profit_margin = ((self.target_price - self.production_cost) / self.production_cost) * 100
            return f"正在生产{self.brand} {self.model}，预期利润率: {profit_margin:.1f}%"

    def calculate_value(self):
        """多态实现 - 厂家计算的是生产价值和市场价值"""
        market_value = self.target_price * 1.1  # 市场价值可能高于目标售价
        return {
            'production_value': self.production_cost,
            'market_value': market_value,
            'profit_potential': market_value - self.production_cost
        }

    def add_technical_spec(self, key, value):
        """添加技术规格"""
        self.technical_specs[key] = value

    def issue_recall(self, reason):
        """发布召回"""
        self.recall_status = True
        return f"{self.brand} {self.model} 发布召回: {reason}"


class OwnerVehicle(Vehicle):
    """车主视角的车辆类"""

    def __init__(self, brand, model, year, license_plate, purchase_price,
                 purchase_date, current_mileage=0):
        super().__init__(brand, model, year, license_plate)
        self.purchase_price = purchase_price
        self.purchase_date = purchase_date
        self.current_mileage = current_mileage
        self.fuel_level = 100
        self.maintenance_history = []
        self.is_running = False

    def get_info(self):
        """多态实现 - 车主关注使用状况和个人信息"""
        base_info = self.get_common_info()
        return (f"{base_info} | 车牌: {self.license_plate} | "
                f"里程: {self.current_mileage}km | 油量: {self.fuel_level}%")

    def perform_action(self):
        """多态实现 - 车主执行驾驶相关动作"""
        if self.is_running:
            return f"正在驾驶{self.brand} {self.model}出行"
        else:
            return f"{self.brand} {self.model}当前停放中"

    def calculate_value(self):
        """多态实现 - 车主计算的是折旧后的个人资产价值"""
        current_year = datetime.now().year
        car_age = current_year - self.year
        # 简单折旧模型：每年折旧15%，最低保留20%价值
        depreciation = min(0.8, car_age * 0.15)
        current_value = self.purchase_price * (1 - depreciation)
        return {
            'purchase_value': self.purchase_price,
            'current_value': current_value,
            'depreciation_rate': depreciation
        }

    def start_engine(self):
        """启动引擎"""
        if self.fuel_level > 0:
            self.is_running = True
            return f"{self.license_plate} 引擎已启动"
        return "油量不足，无法启动"

    def drive(self, distance):
        """驾驶车辆"""
        if not self.is_running:
            return "请先启动引擎"

        fuel_used = distance * 0.1  # 简化油耗计算
        if self.fuel_level >= fuel_used:
            self.current_mileage += distance
            self.fuel_level -= fuel_used
            return f"行驶了{distance}km，剩余油量{self.fuel_level:.1f}%"
        return "油量不足"


class TrafficVehicle(Vehicle):
    """交通管理视角的车辆类"""

    def __init__(self, brand, model, year, license_plate, owner_name,
                 registration_date, emission_standard):
        super().__init__(brand, model, year, license_plate)
        self.owner_name = owner_name
        self.registration_date = registration_date
        self.emission_standard = emission_standard
        self.violations = []
        self.inspection_due = None
        self.set_inspection_due_date()

    def get_info(self):
        """多态实现 - 交管关注合规和监管信息"""
        base_info = self.get_common_info()
        violation_count = len(self.violations)
        inspection_status = self.check_inspection_status()
        return (f"{base_info} | 车主: {self.owner_name} | "
                f"违章次数: {violation_count} | 年检状态: {inspection_status}")

    def perform_action(self):
        """多态实现 - 交管执行监管动作"""
        unpaid_fines = self.calculate_unpaid_fines()
        if unpaid_fines > 0:
            return f"对{self.license_plate}进行违章处理，待缴罚款{unpaid_fines}元"
        else:
            return f"对{self.license_plate}进行常规监管检查"

    def calculate_value(self):
        """多态实现 - 交管计算的是'合规'价值"""
        unpaid_fines = self.calculate_unpaid_fines()
        compliance_score = 100 - (len(self.violations) * 10)  # 违章扣分
        compliance_score = max(0, compliance_score)

        return {
            'compliance_score': compliance_score,
            'unpaid_fines': unpaid_fines,
            'road_safety_value': compliance_score * 100  # 交通安全价值
        }

    def set_inspection_due_date(self):
        """设置年检到期日"""
        registration_date = datetime.strptime(self.registration_date, "%Y-%m-%d")
        self.inspection_due = registration_date + timedelta(days=365)

    def check_inspection_status(self):
        """检查年检状态"""
        if datetime.now() > self.inspection_due:
            return "已过期"
        return "有效"

    def add_violation(self, violation_type, fine_amount, location):
        """添加违章记录"""
        violation = {
            'type': violation_type,
            'fine_amount': fine_amount,
            'location': location,
            'date': datetime.now().strftime("%Y-%m-%d"),
            'paid': False
        }
        self.violations.append(violation)
        return f"已记录违章: {violation_type}"

    def calculate_unpaid_fines(self):
        """计算未缴罚款总额"""
        return sum(v['fine_amount'] for v in self.violations if not v['paid'])
